package cn.ld.module.system.api.user;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.ld.framework.common.util.object.BeanUtils;
import cn.ld.framework.datapermission.core.annotation.DataPermission;
import cn.ld.module.system.api.user.dto.AdminUserOutDTO;
import cn.ld.module.system.dal.entity.dept.DeptEntity;
import cn.ld.module.system.dal.entity.user.AdminUserEntity;
import cn.ld.module.system.service.dept.DeptService;
import cn.ld.module.system.service.user.AdminUserService;
import jakarta.annotation.Resource;
import org.springframework.stereotype.Service;

import java.util.*;

import static cn.ld.framework.common.util.collection.CollectionUtils.convertSet;

/**
 * Admin 用户 API 实现类
 *
 * @author 蓝盾
 */
@Service
public class AdminUserApiImpl implements AdminUserApi {

    @Resource
    private AdminUserService userService;
    @Resource
    private DeptService deptService;

    @Override
    public AdminUserOutDTO getUser(Long id) {
        AdminUserEntity user = userService.getUser(id);
        return BeanUtils.toBean(user, AdminUserOutDTO.class);
    }

    @Override
    public List<AdminUserOutDTO> getUserListBySubordinate(Long id) {
        // 1.1 获取用户负责的部门
        List<DeptEntity> depts = deptService.getDeptListByLeaderUserId(id);
        if (CollUtil.isEmpty(depts)) {
            return Collections.emptyList();
        }
        // 1.2 获取所有子部门
        Set<Long> deptIds = convertSet(depts, DeptEntity::getId);
        List<DeptEntity> childDeptList = deptService.getChildDeptList(deptIds);
        if (CollUtil.isNotEmpty(childDeptList)) {
            deptIds.addAll(convertSet(childDeptList, DeptEntity::getId));
        }

        // 2. 获取部门对应的用户信息
        List<AdminUserEntity> users = userService.getUserListByDeptIds(deptIds);
        users.removeIf(item -> ObjUtil.equal(item.getId(), id)); // 排除自己
        return BeanUtils.toBean(users, AdminUserOutDTO.class);
    }

    @Override
    @DataPermission(enable = false) // 禁用数据权限。原因是，一般基于指定 id 的 API 查询，都是数据拼接为主
    public List<AdminUserOutDTO> getUserList(Collection<Long> ids) {
        List<AdminUserEntity> users = userService.getUserList(ids);
        return BeanUtils.toBean(users, AdminUserOutDTO.class);
    }

    @Override
    public List<AdminUserOutDTO> getUserListByDeptIds(Collection<Long> deptIds) {
        List<AdminUserEntity> users = userService.getUserListByDeptIds(deptIds);
        return BeanUtils.toBean(users, AdminUserOutDTO.class);
    }

    @Override
    public List<AdminUserOutDTO> getUserListByPostIds(Collection<Long> postIds) {
        List<AdminUserEntity> users = userService.getUserListByPostIds(postIds);
        return BeanUtils.toBean(users, AdminUserOutDTO.class);
    }

    @Override
    public void validateUserList(Collection<Long> ids) {
        userService.validateUserList(ids);
    }

}
